<script setup>
import {onMounted, ref, reactive} from "vue";
import {Search} from "@element-plus/icons-vue";
import service from "@/service/service";
import ParameterSettings from './zhiling/ZhiLingParameterSettings.vue'
import ParamDetailDialog from './zhiling/ParamDetailDialog.vue'


// import service from '@/utils/request'

import router from "@/router";
import {listDept} from "@/api/system/dept.js";
import {delSatellitemanage} from "@/api/satellite/satellitemanage.js";
import Sortable from 'sortablejs'
import {
  getSatelliteListSerive,
  canProtocolListSerive,
  InstructTypesSerive,
  getInstructionsOfTypeSerive,
  getDetail,
  getSearchList,
  deleteInstructsSerive,
  getInstructionsBySouSuoTypeSerive,
  ShengChengZhiLingCodeSerive,
  duoxingFaSongZhiLingSerive,
  chaXunYiFaSongZhiLingSerive, shanChuZhunBeiZhiLingSerive,
  zhunBeiFaSunZhiLingSerive, guDingZhiListsSerive,
} from "../../api/satellite/SingleInstructionSending.js";
// 导入store
import store from '@/store'
import {ElMessage, ElMessageBox} from "element-plus";
import { intToHex } from '../../api/satellite/hexConverter';
// 获取当前用户信息
//   const userInfo = store.state.value.user
// 或者直接获取需要的字段
const userId = store.state.value.user.id
const userName = store.state.value.user.name
const nickName = store.state.value.user.nickName

const detailVisible = ref(false)
const currentSentCommandId = ref(null)
//

const tableRef = ref()     // 指向 el-table
const tableData2 = ref([])

const {proxy} = getCurrentInstance()
//import {ElMessage} from "element-plus";

const activeName = ref('')

let subSystemTypes = ref([]);
let instructList = ref([]);
let showInstruct = ref(false);
let satelliteList = ref([]);
let selectedSatelliteId = ref([]);
let selectedSatelliteCode = ref("");
let selectedSatelliteData = ref("");
// 声明一个值为"0"的字符串
const zeroStr = ref('0');

let tableData = reactive([]);
/*let satelliteData = ref("");
let instructionName = ref("");*/
let instructionContent = ref([]);
let absoluteDelayed = ref([{}, {}]);
let dateShow = ref([false, false, false]);
let historyData = ref([]);

let totals = ref(10);
let currentPage = ref(1);
let pageSize = ref(10);

// 参数设置  添加 以下变量
const parameterDialogVisible = ref(false)
const currentInstructionCode = ref('')
const currentInstructionName = ref('')
const currentSatelliteId = ref('')
const selectedSatelliteCodes = ref('')
const currentSatelliteIds = ref([])
const zhunBeiFaSongZhiLingId = ref([])
const rowObject = ref(null)




// 参数设置指令发送指令删除联动操作方法
const canshuFasongShanChuLianDong = (row,b) =>{

  if(b === undefined){
    b = true;
  }
  // 1. 拆成字符串数组
  const hexArr = row.satellite.split(',');

  // 2. 遍历（可按需转成数字）
  const sszu = ref([])
  hexArr.forEach(hex => {
    for (let i = 0; i < satelliteList.value.length; i++) {
      const item = satelliteList.value[i];
      if (item.code === hex) {
        console.log(i, item,item.code, hex, item.id+";@;"+item.code);
        // 拼成字符串并加入数组
        // selectedSatelliteData.value.push(`${item.id};@;${item.code}`);
        sszu.value.push(`${item.id};@;${item.code}`);
        break;        // 立即跳出整个循环
      }
    }
  });
  selectedSatelliteData.value = sszu.value



  getSubSystemTypes();
  activeName.value = row.typesCode
  getInstructList();

  console.log(b,'~~~~~~~~~~~~~~~~11111111111111111111111111111从数据源中找到value匹配的对象~~~~~~~~~~~~~~~~', checkboxRefs ,row.instructionCode)


  setTimeout(() => {
    // 正确的做法：更新响应式数据而非直接操作DOM
    if (!checkedIds.value.includes(row.instructionCode)) {
      // 将指令代码添加到选中数组中
      checkedIds.value = [...checkedIds.value, row.instructionCode];

      const event = {
        target: {
          // checked: true
          checked: b
        }
      }
      // generateInstruction(event, instructionCode, instructionName);

      console.log('更新后的选中状态:', checkedIds.value);
    }
  }, 1500)
}


// 新增：用于保存Sortable实例，方便后续销毁
const sortableInstance = ref(null);
// 打开参数设置对话框的方法
const openParameterSettings = (instructionCode, instructionName) => {

  console.log('打开参数设置对话框的方法  selectedSatelliteId.value : ',selectedSatelliteId.value)
  if (!selectedSatelliteId.value || selectedSatelliteId.value.length === 0) {
    ElMessage.warning('请先选择卫星')
    return
  }

  currentInstructionCode.value = instructionCode
  currentInstructionName.value = instructionName
  currentSatelliteId.value = selectedSatelliteId.value[0]
  currentSatelliteIds.value = selectedSatelliteId.value
  selectedSatelliteCodes.value = weixingBianHaos(selectedSatelliteData.value)
  parameterDialogVisible.value = true
}





// 声明一个对象来存储复选框的引用
const checkboxRefs = ref({});

// 打开参数设置1S对话框的方法
const openParameterSetting1s = (instructionCode, instructionName,row) => {
  console.log('打开参数设置1S对话框的方法  row : ',row)
  console.log('打开参数设置1S对话框的方法  row.id : ',row.id)
  console.log('打开参数设置1S对话框的方法  row.satellite : ',row.satellite)

  // 参数设置指令发送指令删除联动操作方法
  canshuFasongShanChuLianDong(row,true)

  if (!selectedSatelliteId.value || selectedSatelliteId.value.length === 0) {
    ElMessage.warning('请先选择卫星')
    return
  }

  currentInstructionCode.value = instructionCode
  currentInstructionName.value = instructionName
  currentSatelliteId.value = selectedSatelliteId.value[0]
  currentSatelliteIds.value = selectedSatelliteId.value
  zhunBeiFaSongZhiLingId.value = row.id
  selectedSatelliteCodes.value = weixingBianHaos(selectedSatelliteData.value)
  parameterDialogVisible.value = true
}

// 处理选中的卫星编号，返回一个数组
const weixingBianHaos = (selectedSatelliteData) => {
  // 可以在这里处理参数保存后的逻辑
  console.log('参数已保存:@@@@@@@@@@!!!!!!!!!!!!!!!!!', selectedSatelliteData)
  // 结果：['XAE2509', 'aaaa']
  const codeList = computed(() =>
      selectedSatelliteData.map(item => item.split(';@;')[1])
  );
  return codeList.value
}


// 参数保存后的回调
const handleParametersSaved = (parameters) => {
  // 可以在这里处理参数保存后的逻辑
  console.log('参数已保存:parameters+++++++++++++++++++++', parameters)
  // 查询准备发送指令：前端页面主要展示对象列表
  zhunBeiFaSunZhiLing();
  parameterDialogVisible.value = false
}


const getSatelliteList = (currentPage, pageSize) => {

  if (currentPage <= 0) {
    currentPage = 1;
  }

  if (pageSize <= 0) {
    pageSize = 10;
  }

  getSatelliteListSerive(currentPage, pageSize).then(response => {


    satelliteList.value = response.data.records;
    totals.value = response.data.totals;
  }).catch((error) => {
    alert(JSON.stringify(error))
  })
};

// 新增：封装拖拽初始化函数
const initSortable = () => {
  // 1. 先销毁旧的Sortable实例（避免重复绑定）
  if (sortableInstance.value) {
    sortableInstance.value.destroy();
    sortableInstance.value = null;
  }

  // 2. 确保tableRef和tbody存在（DOM已渲染）
  nextTick(() => {
    const tbody = tableRef.value?.$el.querySelector('.el-table__body-wrapper tbody');
    if (!tbody) return;

    // 3. 创建新的Sortable实例并保存到ref中
    sortableInstance.value = Sortable.create(tbody, {
      animation: 150,
      ghostClass: 'sortable-ghost',
      onEnd: (evt) => {
        // 调整数组顺序（逻辑不变）
        const { oldIndex, newIndex } = evt;
        const [moved] = tableData.splice(oldIndex, 1);
        tableData.splice(newIndex, 0, moved);
      }
    });
  });
};

const total = ref(0);
const zhunBeiFaSongTotal = ref(0);

const queryParamsDaiFaSongFenYe2 = {
  pageNum: 1,
  pageSize:99999,
  currentPage: 1,
};
const queryParamsFenYe2 = {
  pageNum: 1,
  pageSize: 2,
  currentPage: 1,
};
const data = reactive({
  queryParamsFenYe: {
    pageNum: 1,
    pageSize: 10,
    currentPage: 1,
    pattern: null,
    name: null,
    code: null,
    state: null,
    operatorId: null,
    times: null,
  },
});

const { queryParamsFenYe} = toRefs(data);

onMounted(() => {
  getSatelliteList(currentPage.value, pageSize.value);
  // 首次初始化拖拽（调用封装函数）
  initSortable();
  // 查询准备发送指令：前端页面主要展示对象列表
  zhunBeiFaSunZhiLing();
  // 加载 已发送指令列表
  chaXunYiFaSongZhiLing();
})
// 新增一个用于强制刷新的key
const collapseKey = ref(0);
const getSubSystemTypes = async () => {

  let selectedSatellite = selectedSatelliteData.value + "";
  console.log('新增一个用于强制刷新的key============++++++++++++++++++',selectedSatelliteData.value)
  let satelliteIdCode = selectedSatellite.split(",");
  if (selectedSatellite === "" || satelliteIdCode.length <= 0) {
    subSystemTypes.value = [];
    return;
  }

  selectedSatelliteCode.value = "";
  selectedSatelliteId.value = [];
  for (let i = 0; i < satelliteIdCode.length; i++) {
    let singleIdCodeStr = satelliteIdCode[i];
    let singleIdCode = singleIdCodeStr.split(";@;");
    selectedSatelliteId.value[i] = singleIdCode[0];
    if (selectedSatelliteCode.value === "") {
      selectedSatelliteCode.value = singleIdCode[1];
    } else {
      selectedSatelliteCode.value += ',' + singleIdCode[1];
    }
  }

  let contents = subSystemTypes.value;
  let len = contents.length;
  if (len !== 0) {
    return;
  }

  const params = {
    id: selectedSatelliteId.value[0],
  }


  InstructTypesSerive(params).then((resp) => {
    if (resp.code === 200) {
      subSystemTypes.value = resp.data;
      collapseKey.value++; // 关键：每次赋值后+1，强制el-collapse重新渲染

    } else {
      alert(resp.msg);
    }

  }).catch((error) => {
    alert(JSON.stringify(error))
  })
}

const getInstructList = () => {

  instructList.value = [];

  if ((activeName.value + "") === "") {
    return;
  }

  const params = {
    satelliteId: selectedSatelliteId.value[0],
    typesCode: activeName.value
  }

  console.log('获取所有指令 ！！！！！！！！params, activeName.value == ！！！！！！！',params, activeName.value);
  getInstructionsOfTypeSerive(params).then((resp) => {

    if (resp.code === 200) {
      console.log(resp.data);
      instructList.value = resp.data;
    } else {
      alert(resp.msg);
    }

  }).catch((error) => {
    alert(JSON.stringify(error))
  })
  showInstruct.value = true;
}

const generateInstruction = (e, code, name) => {

  console.log('generateInstruction ~~~~~~~~~~~~~~~ 复选框  勾选e ,code, name ========== ',e ,code, name);
  if (e.target.checked) {

    getInstructionContent(selectedSatelliteCode, code,name, tableData.length);

    let ck = e.target;
    let row = {
      satelliteData: selectedSatelliteCode.value,
      instructionCode: code,
      instructionName: name,
      instructionCodeName: code + '-' + name,
      instructionContent: "",
      checkbox: ck
    };
    // addRow(row);
  } else {

    if (zhunBeiFaSongZhiLingJiHe.value.length > 0) {
      for (let i = 0; i < zhunBeiFaSongZhiLingJiHe.value.length; i++) {
        let row = zhunBeiFaSongZhiLingJiHe.value[i];
        if (code === row.commandCode) {

          if (!confirm("确定删除第" + (i + 1) + " 行，编号和名称为 ' " + code + "-" + name + " ' 的指令数据吗？")) {
            e.target.checked = true;
            return;
          }


          console.log('========= ',i,row,row.id);
          handleDeleteNode(i,row)

          // zhunBeiFaSongZhiLingJiHe.splice(i, 1);
          // 新增：取消复选框删除行后重新初始化拖拽
          initSortable();
          break;
        }
      }
    }
  }

}

const addRow = (newRow) => {
  // 增加这两个字段
  newRow.showAbsoluteDelayPicker = false   // 是否弹出日期框
  newRow.absoluteDelayTime   = ''         // 绝对延时值
  // 新增：把当前时间写进去
  newRow.sendTime = new Date().toLocaleString();   // 或你要的任意格式
  newRow.currentSatelliteIds = currentSatelliteIds.value;
  let rowNum = tableData.push(newRow);
  dateShow.value[rowNum - 1] = false;
  // 新增：添加行后重新初始化拖拽
  initSortable();
};

const showDates = (checked, rowNum) => {

  if (checked) {
    dateShow.value[rowNum] = true;

  } else {
    dateShow.value[rowNum] = false;
  }
}
// 处理指令码字，每50个字符插入一个换行符
const formatCommandCodeword = (str) => {
  if (!str) return '';
  let result = '';
  // 循环字符串，每50个字符添加一个换行
  for (let i = 0; i < str.length; i++) {
    result += str[i];
    // 每50个字符添加一个换行，但避免在最后一个字符后添加
    if ((i + 1) % 50 === 0 && i !== str.length - 1) {
      result += '\n';
    }
  }
  return result;
};
const getInstructionContent = (satelliteCodes, instructionCode, instructionName, rowNum) => {

  console.log('调用获取指令方法时，传递的参数：', satelliteCodes, instructionCode, rowNum);

  let selectedSatellite = selectedSatelliteData.value + "";
  let satelliteIdCode = selectedSatellite.split(",");
  console.log('调用获取指令方法时，循环satelliteIdCode 的值：', satelliteIdCode);
  console.log(satelliteCodes, instructionCode, rowNum);
  let param_a = [];
  for (let i = 0; i < satelliteIdCode.length; i++) {
    let param_b = {};
    let singleIdCodeStr = satelliteIdCode[i];

    console.log('调用获取指令方法时，循环 singleIdCodeStr 的值：', singleIdCodeStr);
    let singleIdCode = singleIdCodeStr.split(";@;");
    console.log('调用获取指令方法时，循环 singleIdCode 的值：', singleIdCode);
    param_b.satelliteId = singleIdCode[0];
    param_b.scId = singleIdCode[1];
    param_b.instructionCode = instructionCode;
    param_b.instructionName = instructionName;
    param_b.satelliteCodes = satelliteCodes;
    console.log('调用获取指令方法时，循环 param_b 的值：', param_b);
    param_a.push(param_b);
  }
  console.log('调用获取指令方法时，循环 param_a 的值：', param_a);
  let params = {
    instructVoList: param_a,
    userId: userId,
    userName: userName,
    nickName: nickName,
  }
//   getInstructionsOfTypeSerive(params).then((resp) => {
  ShengChengZhiLingCodeSerive(params).then((resp) => {
    if (resp.code === 200) {
      zhunBeiFaSunZhiLing()



      /*      tableData.forEach((item, index) => {
              if (item.instructionCode === resp.data[0].instructionCode) {
                item.instructionContent = resp.data[0].instructionContent
                item.instructionContentTitle = resp.data[0].instructionContent
              }
              item.age += 1;
            });
            instructionContent.value[rowNum] = resp.data[0].instructionContent;*/
    } else {
      alert("错误代码：" + code + "; 错误消息：" + message);
    }


  }).catch((error) => {
    alert(error)
  })
}
// duoxingFaSongZhiLingSerive  多星发送指令
const handleSend = (row) => {



  // 参数设置指令发送指令删除联动操作方法
  // canshuFasongShanChuLianDong(row,true)

  /*
    absoluteDelayTime: ""
    absoluteDelayTime:"2025-08-29 12:00:00"
    instructionCode: "TCTY0001"
    instructionCodeName: "TCTY0001-软件复位"
    instructionContent: "1ACFFC1D000112131301800210000000000100001103C001008335260000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020202020202021E1E1E1E1E1E1E1E1E1E1E1E1E00000000000000000000000000F407AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADBF0"
    instructionName: "软件复位"
    satelliteData: "0xA1"
    sendTime: "2025/8/26 15:55:33"
    showAbsoluteDelayPicker: true
    showAbsoluteDelayPicker: false
    */
  /** 卫星唯一标识 satelliteId */
  /** 轨道航天器设备编码 deviceCode */
  /** 指令系统代号  commandCode */
  /** 指令显示名称  commandName */
  /** 指令详细内容 commandContent */
  /** 指令码字/校验字 commandCodeword */
  /** 绝对延时(毫秒) absoluteDelay */
      // :satelliteIds="currentSatelliteIds"

  const rr = row
  console.log('多星发送指令 rr -- 前 ',rr);
  console.log('多星发送指令  -- 前 ',tableData);
  console.log('多星发送指令  -- 前 ',row);
  console.log(row.absoluteDelayTime);
  console.log(row.instructionCode);

  let params = {
    absoluteDelayTime: row.absoluteDelayTime,
    commandCode: row.instructionCode,
    commandName: row.instructionName,
    commandContent: row.instructionContent,
    satelliteIds: currentSatelliteIds.value,
    showAbsoluteDelayPicker: row.showAbsoluteDelayPicker,
    satelliteData: row.satelliteData,
    satellite: row.satellite,
    userId: userId,
    userName: userName,
    nickName: nickName,
  }
  console.log(params);
// 多星发送指令   ShengChengZhiLingCodeSerive
  duoxingFaSongZhiLingSerive(params).then((resp) => {
    console.log('接收返回结果resp： ', resp);
    console.log('多星发送指令  1-- 后 ',tableData);
    console.log('多星发送指令  1-- 后 ',row);
    if (resp.code === 200) {
      proxy.$modal.msgSuccess("发送成功");
      // 查询已经发送的指令
      chaXunYiFaSongZhiLing()
      // 关闭弹出框
      detailDlgVisible.value = false
    } else {
    }
  }).catch((error) => {
    alert(error)
  })

  console.log('多星发送指令 rr -- 后 ',rr.instructionCode+'-'+rr.instructionName,rr);
  console.log('多星发送指令  2-- 后 ',tableData);
  console.log('多星发送指令  2-- 后 ',row);
  console.log('多星发送指令 instructList 2-- 后 ',instructList);

// rr.instructionCode / rr.instructionName 是你当前要删除的那一项的拼接键

  // 假设要删除 instructionCodeName 等于某个值的项
  const key = `${rr.instructionCode}-${rr.instructionName}`

  const idx = tableData.findIndex(item => item.instructionCodeName === key)
  if (idx !== -1) {
    tableData.splice(idx, 1)   // 原地删除一项
  }
  // 取消复选框勾选
  uncheckById(rr.instructionCode)

  // 把过滤后的结果再塞回去，触发响应式更新
  // Object.assign(tableData, tableData.filter(item => item.instructionCodeName !== key));
  /*

    const tableDataTemp = ref([])
    tableData.forEach((item, index) => {
      console.log('rr.instructionCode+\'-\'+rr.instructionName', rr.instructionCode+'-'+rr.instructionName);
      console.log('item.instructionCodeName ', item.instructionCodeName);
      console.log('<UNK>', index, item);
      if(item.instructionCodeName !== rr.instructionCode+'-'+rr.instructionName) {
        tableDataTemp.value.push(item);
        // 把过滤后的结果再塞回去，触发响应式更新
        // Object.assign(tableData, tableData.filter(item => item.instructionCodeName !== key));
      }
    })

    console.log('多星发送指令  333333--tableDataTemp 后 ',tableDataTemp);
    tableData.splice(0)         // 清空
    tableData.push(...tableDataTemp)  // 添加新数据
  */

}

const satelliteCommandList = ref([]);
const zhunBeiFaSongZhiLingJiHe = ref([]);





/* 已选行数组，外部可直接读取 */
const selectedRows = ref([])

/* 当用户勾选/取消任意行时触发 */
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

/* 全选 / 取消全选 */
const toggleAll = () => {
  const table = tableRef.value
  if (!table) return
  // 如果当前有没选中的就全选，否则取消全选
  const needSelect = selectedRows.value.length < zhunBeiFaSongZhiLingJiHe.value.length
  needSelect
      ? table.toggleAllSelection()
      : table.clearSelection()
}

/* 一键删除已选 */
const delAll = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请先勾选要删除的行')
    return
  }
  ElMessageBox.confirm(`确定删除选中的 ${selectedRows.value.length} 条记录？`, '提示')
      .then(() => {

        /* 根据主键过滤掉已选行 */
        const codes = selectedRows.value.map(r => r.instructionCode)
        const ids = selectedRows.value.map(r => r.id)
        console.log('确定删除选中的:',codes,ids)


        // 多星发送指令   ShengChengZhiLingCodeSerive
        deleteInstructsSerive(ids).then((resp) => {
          console.log('删除 准备指令接收返回结果resp： ', resp);
          console.log('删除 准备指令  1-- 后 ',tableData);
          console.log('删除 准备指令  1-- 后 ',row);
          if (resp.code === 200) {
            proxy.$modal.msgSuccess("删除成功");
            // 查询已经发送的指令
            zhunBeiFaSunZhiLing()
          } else {
          }
        }).catch((error) => {
          // alert(error)
          ElMessage.error(error)
        })



        zhunBeiFaSongZhiLingJiHe.value =
            zhunBeiFaSongZhiLingJiHe.value.filter(r => !codes.includes(r.instructionCode))
        /* 清空已选 */
        tableRef.value.clearSelection()
        ElMessage.success('删除成功')
      })
      .catch(() => {})
}

/* 如果外面需要“勾选了哪些行”，直接读 selectedRows 即可 */
defineExpose({ selectedRows })


































// 查询准备发送指令：前端页面主要展示对象列表
const zhunBeiFaSunZhiLing = () => {
  console.log('查询准备发送指令1111111111111111111111==');
  zhunBeiFaSunZhiLingSerive(queryParamsDaiFaSongFenYe2).then((resp) => {
    console.log('查询准备发送指令@@@1122  resp ==',resp);
    console.log('查询准备发送指令@@@1122 resp.rows==',resp.rows);
    if (resp.code === 200) {
      console.log(resp.rows);
      tableData.value = resp.rows;
      zhunBeiFaSongZhiLingJiHe.value = resp.rows;
      console.log('查询准备发送指令@@@1122 tableData.value************************8==',tableData.value);
      zhunBeiFaSongTotal.value = resp.total;
      // instructList.value = resp.data;
    } else {
      proxy.$modal.errorMsg(resp.msg);
    }
  }).catch((error) => {
    proxy.$modal.errorMsg(error);
  })
}

// 查询已经发送的指令
const chaXunYiFaSongZhiLing = () => {


  chaXunYiFaSongZhiLingSerive(queryParamsFenYe2).then((resp) => {
    console.log('查询已经发送的指令@@@1122  resp ==',resp);
    console.log('查询已经发送的指令@@@1122 resp.rows==',resp.rows);
    if (resp.code === 200) {
      console.log(resp.rows);
      satelliteCommandList.value = resp.rows;
      total.value = resp.total;
      // instructList.value = resp.data;
    } else {
      proxy.$modal.errorMsg(resp.msg);
    }
  }).catch((error) => {
    proxy.$modal.errorMsg(error);
  })
  showInstruct.value = true;
}

const zhunBeiShanChuZhiLingId = ref([])



// 删除 准备指令
const handleDelete = (index, row) => {
  if (!confirm("确定删除第 " + (index + 1) + " 行，编号和名称为 ' " + row.instructionCodeName + " ' 的指令数据吗？")) {
    return;
  }

  zhunBeiShanChuZhiLingId.value.push( row.id);
  let params = {
    ids: zhunBeiShanChuZhiLingId.value,
  }
  console.log(params);
// 多星发送指令   ShengChengZhiLingCodeSerive
  shanChuZhunBeiZhiLingSerive(params,row.id).then((resp) => {
    console.log('删除 准备指令接收返回结果resp： ', resp);
    console.log('删除 准备指令  1-- 后 ',tableData);
    console.log('删除 准备指令  1-- 后 ',row);
    if (resp.code === 200) {
      proxy.$modal.msgSuccess("删除成功");
      // 查询已经发送的指令
      chaXunYiFaSongZhiLing()
    } else {
    }
  }).catch((error) => {
    alert(error)
  })

  // 参数设置指令发送指令删除联动操作方法
  //  canshuFasongShanChuLianDong(row,false)
  zhunBeiFaSunZhiLing()


  tableData.splice(index, 1);
  let ck = row.checkbox;
  if (ck) {
    ck.checked = false;
  }
  // 新增：删除行后重新初始化拖拽
  initSortable();
}

// 删除 准备指令
const handleDeleteNode = (index, row) => {
  zhunBeiShanChuZhiLingId.value.push( row.id);
  let params = {
    ids: zhunBeiShanChuZhiLingId.value,
  }
  console.log(params);
// 多星发送指令   ShengChengZhiLingCodeSerive
  shanChuZhunBeiZhiLingSerive(params,row.id).then((resp) => {
    console.log('删除 准备指令接收返回结果resp： ', resp);
    console.log('删除 准备指令  1-- 后 ',tableData);
    console.log('删除 准备指令  1-- 后 ',row);
    if (resp.code === 200) {
      proxy.$modal.msgSuccess("删除成功");
      // 查询已经发送的指令
      chaXunYiFaSongZhiLing()
    } else {
    }
  }).catch((error) => {
    alert(error)
  })

  // 参数设置指令发送指令删除联动操作方法
  zhunBeiFaSunZhiLing()


  tableData.splice(index, 1);
  let ck = row.checkbox;
  if (ck) {
    ck.checked = false;
  }
  // 新增：删除行后重新初始化拖拽
  initSortable();
}
const getSendHistory = (currentPage, pageSize) => {

  if (currentPage <= 0) {
    currentPage = 1;
  }
  if (pageSize <= 0) {
    pageSize = 10;
  }
  canProtocolListSerive(currentPage, pageSize).then(response => {
    historyData.value = response.data.data;
    totals.value = response.data.totals;
  }).catch((error) => {
    alert(JSON.stringify(error))
  })


  /*
  service.get('/apis/canProtocolList', {
    params: {
      currentPage: currentPage,
      pageSize: pageSize
    }

  }).then((resp) => {
    let result_str = JSON.stringify(resp.data);
    let resultJSON = JSON.parse(result_str);
    let data_str = JSON.stringify(resultJSON['data'] || resultJSON.data);
    let dataJSON = JSON.parse(data_str);
    let code = resultJSON['code'] || resultJSON.code;
    let message = resultJSON['message'] || resultJSON.message;
    if (code === "0") {
      historyData.value = dataJSON.records;
      totals.value = dataJSON.totals;
    } else {
      alert(message);
    }

  }).catch((error) => {
    alert(JSON.stringify(error))
  })
  */


};

// 处理每页数量变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  const newTotalPages = Math.ceil(totals.value / newSize);
  currentPage.value = Math.min(currentPage.value, newTotalPages) || 1;

  getSendHistory(currentPage.value, pageSize.value);
};

// 处理页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;

  getSendHistory(currentPage.value, pageSize.value);
};



// 存储勾选的ID数组（v-model绑定的数组）
const checkedIds = ref([]);
// 根据ID取消勾选的方法
const uncheckById = (code) => {
  // 从数组中移除该ID，即可取消勾选
  checkedIds.value = checkedIds.value.filter(id => id !== code);
};

const viewParams = (id) => {
  currentSentCommandId.value = id
  detailVisible.value = true
}





import { computed } from 'vue'

const detailDlgVisible = ref(false)
const currentRow       = ref({})
const paramCache       = new Map()
const zhiLingMaZi      = ref('')
const zhiLingMaZiId      = ref(null)
const zhiLingMaZiCode      = ref(null)
const zhiLingMaZiName      = ref(null)
const zhiLingMaZiCodeName      = ref(null)
const zhiLingMaZiWeiXing      = ref(null)
const zhiLingFenZu      = ref([])
const caoZuoYuan = ref('')
const dangQianRen = ref('')
//
//
// 组1   32bits 同步序列
const zu1 = ref('')
// 组2
// 16bits
// 08bits
// 08bits
// 轨道面标识
// 航天器标识(SCID)
// 设备标识
const zu2 = ref('')
//
//
// 组3
// 1bit
// 1bit
// 1bit
// 1bit
// 4bits
//
// 标识域类型
// 回放标识
// 旁路/顺序控制标志
// 协议控制命令标志
// 保留
const zu3 = ref('')
//
//
// 组4
// 3bits
// 5bits
//
// 保留
// 帧长度
const zu4 = ref('')
//
//
// 组5
// 4bits
// 4bits
// 8bits
//
// 服务类型
// 信道类型
// 虚拟信道标识(VCID)
const zu5 = ref('')
//
//
// 组6 32bits
// 虚拟信道帧计数(VCFC)
const zu6 = ref('')
//
// 组7
// 5bits
// 11bits
//
// 保留域
// 首导头指针
const zu7 = ref('')
//
//
// 组8
// 3bits
// 1bit
// 1bit
// 7bits
// 4bits
//
// 版本号
// 包类型
// 副导头标识
// 过程标识符-模块标识
// 过程标识符-数据类型
const zu8 = ref('')
//
//
// 组9
// 2bits
// 14bits
//
//
// 包序列控制-包序列标识
// 包序列控制-包序列计数
const zu9 = ref('')
//
//
//
// 组10
// 16bits
// 包长度
const zu10 = ref('')
//
// 组11
// 16bits
// 指令标识
const zu11 = ref('')
//
// 组12
// N*16bits
// 参数
const zu12 = ref('')
//
// 组13
// 16bits
// 差错域
const zu13 = ref('')
//
// 组14
// L-N Bytes
// 空闲数据区
//
const zu14 = ref('')
// 组15
// 16bits
// 差错控制域（2字节）
const zu15 = ref('')

const guDingZhiLists = ref([])

// 打开弹窗
const openDetailDlg = (row) => {

  rowObject.value = row
  console.log('打开弹窗11111111122222222:',row)
  caoZuoYuan.value = row.operator;
  dangQianRen.value = userId+'-'+userName+'-'+nickName
  currentRow.value = row
  detailDlgVisible.value = true
  getGuDingZhiLists(row)
}

// 关闭弹窗
const handleClose = () => {
  rowObject.value = ref(null)
  detailDlgVisible.value = false
}



/* 获取指令的固定值信息 */
const getGuDingZhiLists = (row) => {

  const params = {
    typesCode: row.typesCode,
    commandCode: row.commandCode,
    satellite: row.satellite,
    versionNo: row.versionNo,
  }
  guDingZhiListsSerive(params).then((res) => {
    console.log('接收返回结果res： ', res);
    if (res.code === 200) {
      // proxy.$modal.msgSuccess("发送成功");
      // 查询已经发送的指令
      guDingZhiLists.value = res.rows
    } else {
    }
  }).catch((error) => {
    alert(error)
  })
}
// 将码字分段（每 50 字符）
const segments = computed(() => {
  const str = currentRow.value.instructionContent || ''
  zhiLingMaZiId.value = currentRow.value.id
  zhiLingMaZiCode.value = currentRow.value.commandCode
  zhiLingMaZiName.value = currentRow.value.commandName
  zhiLingMaZiCodeName.value = currentRow.value.instructionCodeName
  zhiLingMaZiWeiXing.value = currentRow.value.selectedSatelliteData


// 组1   32bits 同步序列
    zu1.value = str.substring(0,8)
// 组2
// 16bits
// 08bits
// 08bits
// 轨道面标识
// 航天器标识(SCID)
// 设备标识    .replace(/(.{2})/g, '$1 ').trimEnd()
    zu2.value = str.substring(8,16).replace(/(.{2})/g, '$1 ').trimEnd()
//
//
// 组3
// 1bit
// 1bit
// 1bit
// 1bit
// 4bits
//
// 标识域类型
// 回放标识
// 旁路/顺序控制标志
// 协议控制命令标志
// 保留
    zu3.value = str.substring(16,18)
//
//
// 组4
// 3bits
// 5bits
//
// 保留
// 帧长度
    zu4.value = str.substring(18,20)
//
//
// 组5
// 4bits
// 4bits
// 8bits
//
// 服务类型
// 信道类型
// 虚拟信道标识(VCID)
    zu5.value = str.substring(20,24)
//
//
// 组6 32bits
// 虚拟信道帧计数(VCFC)
    zu6.value = str.substring(24,32).replace(/(.{2})/g, '$1 ').trimEnd()
//
// 组7
// 5bits
// 11bits
//
// 保留域
// 首导头指针
    zu7.value = str.substring(32,36)
//
//
// 组8
// 3bits
// 1bit
// 1bit
// 7bits
// 4bits
//
// 版本号
// 包类型
// 副导头标识
// 过程标识符-模块标识
// 过程标识符-数据类型
    zu8.value = str.substring(36,40)
//
//
// 组9
// 2bits
// 14bits
//
//
// 包序列控制-包序列标识
// 包序列控制-包序列计数
    zu9.value = str.substring(40,44)
//
//
//
// 组10
// 16bits
// 包长度
    zu10.value = str.substring(44,48)

  // 16进制转换10进制==字节数*2 ==多个符号（文档中计算包长时 特意减了一字节（两个符号），在此需要特意加一个字节（两个符号））
  const num = parseInt(str.substring(44,48), 16)*2+2;
  console.log('包长度====>','16进制：', zu10.value,'10进制：',num)

//
// 组11
// 16bits
// 指令标识
    zu11.value = str.substring(48,52)
//
// 组12
// N*16bits
// 参数
  // 52到指令标识的坐标，num=包长=（数据域=指令标识+参数+差错域）
  let zz12 = 52+num-8
  let zz13 = zz12+4
  zu12.value = str.substring(52,zz12)
//
// 组13
// 16bits
// 差错域
    zu13.value =  str.substring(zz12,zz13)
//
// 组14
// L-N Bytes
// 空闲数据区
//
    zu14.value = ''
// 组15
// 16bits
// 差错控制域（2字节）
  let sLeng = str.length
    zu15.value = str.substring(sLeng-4,sLeng)





  zhiLingMaZi.value = str

  const res = []
  for (let i = 0; i < str.length; i += 50) {
    res.push({
      offset: i,
      codeword: str.slice(i, i + 50),
      param: '',
      fixed: ''
    })
  }
  return res
})

// 查询参数信息
const queryParam = async (cmdCode) => {
  if (paramCache.has(cmdCode)) {
    fillSegments(paramCache.get(cmdCode))
    return
  }
  try {
    // 示例接口：返回 [{offset, param, fixed}, ...]
    const { data } = await service.post('/api/cmd/paramDetail', { commandCode: cmdCode })
    paramCache.set(cmdCode, data)
    fillSegments(data)
  } catch (e) {
    ElMessage.error('查询参数信息失败：' + e.message)
  }
}

// 把接口数据映射到对应 offset 的片段
const fillSegments = (list) => {
  list.forEach(item => {
    const idx = Math.floor(item.offset / 50)
    if (segments.value[idx]) {
      segments.value[idx].param = item.param
      segments.value[idx].fixed = item.fixed
    }
  })
}





// 生成默认内容数组，按顺序填充
const defaultContent = ref(
    Array.from({ length: 81 }, (_, index) => `默认内容${index + 1}`)
);

const size = ref('small');
/**
 * 计算公式 → 16 进制结果
 * @param {string} formula   公式，如 '0.1*Par'
 * @param {object} vars      变量对象，如 {Par: 123}
 * @param {number} [decimals] 保留小数位（优先级高于公式内小数点计数）
 *                         当 decimals === undefined 或 null 时，才用公式内小数点计数
 * @param {number} [hexLen]  结果 16 进制字符串总长度（高位补 0）
 * @returns {string}  大写 16 进制字符串，已补 0
 */
const calcToHex = (formula, vars, decimals = null, hexLen = 0) => {
  /* 1. 确定保留小数位 */
  let scale;
  if (decimals == null) {
    // 未传 decimals 或显式传 null：按公式中小数点个数
    scale = (formula.match(/\./g) || []).length;
  } else {
    // 传了有效 decimals，直接用它
    scale = decimals;
  }

  /* 2. 注入变量 */
  let expr = formula;
  for (const [k, v] of Object.entries(vars)) {
    expr = expr.replace(new RegExp(`\\b${k}\\b`, 'g'), v);
  }

  /* 3. 计算并保留小数 */
  const fn = new Function(`return (${expr})`);
  const resDec = Number(fn()).toFixed(scale); // 字符串，已四舍五入
  const resInt = Math.round(Number(resDec) * 10 ** scale); // 真正整型值（可选）

  /* 4. 结果转 16 进制 */
  let resHex = Math.round(Number(resDec)).toString(16).toUpperCase();
  const targetLen = hexLen > 0 ? hexLen : (resHex.length % 2 ? resHex.length + 1 : resHex.length);
  resHex = resHex.padStart(targetLen, '0');

  return resHex;
};
/**
 * 根据公式反向求变量值
 * @param {string} formula   公式，如 'Math.scalb(Lim/360,24)'
 * @param {string} paramName 变量名，如 'Lim'
 * @param {string} hexResult 结果16进制字符串（无前缀0x），如 '64'
 * @returns {{dec:number, hex:string}} 变量10进制值与16进制字符串（大写、高位补0）
 */
const reverseCalc = (formula, paramName, hexResult) => {
  // 1. 16 进制 → 10 进制
  const target = Number(`0x${hexResult}`);

  // 2. 把公式中的变量替换成占位符 x
  const expr = formula.replace(new RegExp(`\\b${paramName}\\b`, 'g'), 'x');

  // 3. 构建可执行函数
  const fn = new Function('x', `return (${expr});`);

  // 4. 二分法反解（边界足够大）
  let left = -1e9, right = 1e9, mid, value;
  const EPS = 1e-6;
  for (let i = 0; i < 100; i++) {
    mid = (left + right) / 2;
    value = fn(mid);
    if (Math.abs(value - target) < EPS) break;
    if (value < target) left = mid;
    else right = mid;
  }

  // 5. 10 进制
  const dec = Math.round(mid);

  // 6. 16 进制：大写、高位补 0，保证长度为 2 的倍数
  let hex = dec.toString(16).toUpperCase();
  if (hex.length % 2) hex = '0' + hex;

  // return { dec, hex };
  return hex;
}


/* 颜色映射表，可以按需要改 */
const colorMap = {
    '无符号整型': '#d64c47',   // 亮玫红
    '带符号整型': '#00a8ff',   // 亮电蓝
    '16进制':      '#00e676',   // 荧光绿
    '字典':      '#268a1b',   // 霓虹粉
    '布尔':      '#8a7c5a'    // 亮琥珀
}

const shiYongCanShuGeshu = ref('')
/* 计算带样式的拼接串 */
const styledHexString = computed(() => {
  let str = ''
  let count = 0
  shiYongCanShuGeshu.value = `使用设置的 `+guDingZhiLists.value.length+` 个参数（每行24个16进制参数）`

  str = processList(guDingZhiLists.value)

  console.log('对参数集合进行 长度为1的判断和处理：',str)
  if(str !== '' && str !== null && str.length>0)
    return str



  guDingZhiLists.value.forEach((item, idx) => {
    if (count && count % 24 === 0) str += '<br/>'   // 每 6 组换行
    count++

    // 计算本段的 hex
    let hex = ''

    if (item.processManner === '计算公式' || item.processManner === '公式计算') {
      // 变量名是运行时才拿到的
      const varName = item.parameterCode;   // 也可以是 'CmdParam2'、'PAR' ...
      const varValue = item.defaultValue;

      const vars = { [varName]: varValue };   // 计算属性写法
      hex = calcToHex(item.parameterDefinition, vars, 0,item.parameterLength / 4);
      // console.log('公式计算======',hex); // CmdParam1 = 180(0xB4) , 结果 = 65536(0x010000)
    }else {
      if (item.parameterType === '无符号整型') {
        hex = Number(item.defaultValue).toString(16).toUpperCase()
      } else {
        hex = intToHex(item.defaultValue, item.parameterLength / 4)
      }

      hex = padZero(hex, item.parameterLength / 4)
    }

    // 样式：颜色 + 是否加粗
    const color = colorMap[item.parameterType] || '#000'
    const weight = item.parameterSequence % 2 === 0 ? 'bold' : 'normal'
    str += `<span style="color:${color};font-weight:${weight};font-size:18px;margin-right:8px;">${hex}</span>`
  })

  return str
})


// utils/string.ts 给字符串高位补 0 的通用方法是使用
const padZero = (str, length)  => {
  return String(str).padStart(length, '0');
}




/**
 * 处理逻辑
 * @param {Array<{ parameterLength: string, defaultValue: string }>} list
 * @returns {string|null}
 */
const processList = (list) => {
  if (!Array.isArray(list) || list.length === 0) return null;

  // 1. 解析 parameterLength
  const lengths = list.map(item => Number(item.parameterLength));

  // 2. 收集连续 <8 的段长度
  const segments = [];
  let current = 0;

  // 判断是否有小于8的，若没有则返回 null
  let currentTep = 0;
  for (const len of lengths) {
    if (len < 8) {
      currentTep = len;
      break;
    }
  }
  // 没有小于8的 则返回，使用原来逻辑
  if(currentTep === 0){
    return '';
  }

  for (const len of lengths) {
    if (len < 8) {
      current += len;
    } else {
      if (current > 0) {
        segments.push(current);
        current = 0;
      }
    }
  }
  if (current > 0) segments.push(current);

  // 3. 判断是否所有段都是 8 的倍数
  const allMatch = segments.every(len => len % 8 === 0);
  if (!allMatch) return null;

  // 4. 拼接结果
  let result = '';
  let binaryBuffer = '';

  for (let i = 0; i < list.length; i++) {
    const len = Number(list[i].parameterLength);
    let val = list[i].defaultValue;

    if (len < 8) {
      binaryBuffer += val;
    } else {
      // 先处理缓存的二进制字符串
      if (binaryBuffer.length > 0) {
        const hex = BigInt('0b' + binaryBuffer).toString(16);
        result += hex;
        binaryBuffer = '';
      }

      console.log('处理十六进制或十进制字符串 1111====>>>>', result);
      console.log('处理十六进制或十进制字符串 val====>>>>  ', val);
      // 处理十六进制或十进制字符串
      if (val.startsWith('0x') || val.startsWith('0X')) {
        val = val.slice(2); // 去掉 0x
        console.log('处理十六进制或十进制字符串去掉 0x  len, val ====>>>>  ',len, val);
        val = val.padStart(len/4, '0');
        result += val;

        console.log('处理十六进制或十进制字符串 2222====>>>>', result);
      } else {
        try {
          const hex = BigInt(val).toString(16);
          result += hex;
        } catch {
          result += '0';
        }
      }
    }
  }

  // 处理尾巴
  if (binaryBuffer.length > 0) {
    result += BigInt('0b' + binaryBuffer).toString(16);
  }

  return result.toUpperCase(); // 可选：统一大写
}




const keyword = ref('')
const resultList = ref([])
const detail = ref(null)
const showList = ref(false)

/* 实时搜索：输入框变化即调后台 */
let timer = null
const onInput = (val) => {
  clearTimeout(timer)
  timer = setTimeout(() => {
    searchHandler(val)
  }, 300)
}

/* 统一搜索方法：支持空串清空列表 */
const searchHandler = async (val = keyword.value) => {
  if (!val.trim()) {
    resultList.value = []
    show
    List.value = false
    return
  }
  const params = {
    satelliteId: selectedSatelliteId.value[0],
    typesCode: activeName.value,
    keyword: val,
  }

  const data = await getSearchList(params) // 见下方api
  console.log('getSearchList+++++++++++++++++++++',data)
  resultList.value = data || []
  showList.value = true
}

/* 点击列表项：再调后台拿详情 */
const chooseItem = async (item) => {
  detail.value = await getDetail(item.id) // 见下方api
  showList.value = false // 收起下拉
}

/* 点击页面其他地方关闭下拉 */
watch(showList, (v) => {
  const close = (e) => {
    if (!e.target.closest('.instruct-search') && !e.target.closest('.el-card')) {
      showList.value = false
      document.removeEventListener('click', close)
    }
  }
  if (v) document.addEventListener('click', close)
})

</script>

<template>
  <div class="instruct-send-main">
    <div class="branch-types-left">

<br/>
<!--

      <span class="instruct-search">
        <input type="text" style="width: 60%;border-radius: 6px;border-color: #bebebe;border-style: none"/>
        <el-button type="primary" :icon="Search" style="width: 20%;"/>
      </span>

-->





      <el-select v-model="selectedSatelliteData" multiple placeholder="选择卫星" style="width: 90%"
                 @change="getSubSystemTypes()">
        <el-option
            v-for="item in satelliteList"
            :key="item.id"
            :label="item.name"
            :value="item.id + ';@;' + item.code">
        </el-option>
      </el-select>












      <span class="instruct-search">
        <el-input
            v-model="keyword"
            placeholder="请输入关键词"
            style="width: 60%; border-radius: 6px"
            clearable
            @input="onInput"
        />
        <!-- 蓝色边框按钮 -->
        <el-button
            type="primary"
            :icon="Search"
            style="width: 20%; margin-left: 8px"
            class="search-btn"
            @click="searchHandler"
        >
          搜索
        </el-button>
      </span>

    <!-- 2. 实时下拉列表 -->
    <el-card
        v-if="showList && resultList.length"
        shadow="hover"
        style="margin-top: 8px"
    >
      <div
          v-for="(item, idx) in resultList"
          :key="idx"
          class="search-item"
          @click="getInstructionContent(getInstructionContent,item.instructionCode,item.instructionName,0)"
      >
        {{ item.instructionCode }}-{{ item.instructionName }}
      </div>
    </el-card>

    <!-- 3. 点击后加载的详情 -->
    <el-card v-if="detail" style="margin-top: 12px">
      <template #header>选中详情</template>
      <pre>{{ JSON.stringify(detail, null, 2) }}</pre>
    </el-card>















      <p/>
      <span>全部指令</span>


      <el-scrollbar max-height="80%"
                    style="padding: 2px;
                    height: 500px;
                    padding: 0px;
                    background: white;
                  "
      >

        <el-collapse v-model="activeName" class="instruct-collapse" accordion @change="getInstructList()"
                     :key="collapseKey">
          <el-collapse-item
              v-for="(typeItem, typeIndex) in subSystemTypes"
              :title="typeItem.moduleName"
              :name="typeItem.typesCode"
              :key="typeIndex"
          >
            <div
                v-show="showInstruct"
                v-for="(instructItem, instructIndex) in instructList"
                :key="instructIndex"
                style="
                        display: flex;
                        align-items: center;      /* 垂直居中 */
                        margin-left: 10px;
                        gap: 6px;                 /* 元素间距 */
                      "
            >
              <!-- 复选框 -->
              <input
                  type="checkbox"
                  v-model="checkedIds"
                  :id="instructItem.instructionCode"
                  :value="instructItem.instructionCode"
                  :ref="el => checkboxRefs[instructItem.instructionCode] = el"
                  @change="generateInstruction($event, instructItem.instructionCode, instructItem.instructionName)"
              />
              <!-- 指令代码 -->
              <span>{{ instructItem.instructionCode }}</span>
              <!-- 指令名称（超长省略） -->
              <span
                  style="
                          flex: 1 1 0;
                          white-space: nowrap;
                          overflow: hidden;
                          text-overflow: ellipsis;
                        "
                  :title="instructItem.instructionName"
              >
      {{ instructItem.instructionName }}
    </span>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-scrollbar>
    </div>

























    <div class="send-instruct-right">
<!--
      <el-row style="position: relative;top: 0;height: 10%;min-height: 50px; width: 100%;" >
        <el-col :span="24">
          <el-divider content-position="left">准备发送（共{{zhunBeiFaSongTotal}}条）</el-divider>
        </el-col>
      </el-row>
-->

      <!-- 标题栏：全部删除 + 准备发送 -->
      <el-divider content-position="left">
        <el-button
            type="danger"
            size="small"
            @click="delAll"
            style="margin-right:12px;">
          全部删除
        </el-button>
        准备发送（共{{ zhunBeiFaSongTotal }}条）
      </el-divider>



      <!-- 关键：添加表格滚动容器，高度设为屏幕60%（60vh），超出滚动 -->
<!--      <div style="height: 50vh; overflow-y: auto; margin: 0 16px;" >-->

     <div  class="table-outer-container">
       <!-- 工具栏：全部删除 -->
<!--
       <div style="margin-bottom:6px;">
         <el-button type="danger" size="small" @click="delAll">全部删除</el-button>
       </div>
       -->
      <el-table :data="zhunBeiFaSongZhiLingJiHe"  class="custom-table"

                ref="tableRef"
                :height="`calc(55vh - 50px)`"
                 border
                row-key="instructionCode"
       @selection-change="handleSelectionChange"
      >
        <!-- 1. 复选框列 -->
        <el-table-column type="selection" width="46" align="center" />
        <el-table-column label="序号" style="width: 20px">
          <template #default="scope">
            <div style="align-items: center">
              <span style="margin-left: 0">{{ scope.$index + 1 }}</span>
            </div>
          </template>
        </el-table-column>
        <!--
                <el-table-column label="卫星编号" align="center" prop="selectedSatelliteData" />
        -->

        <el-table-column label="卫星编号"  align="center" prop="selectedSatelliteData">
          <template #default="scope">
            <el-tooltip
                placement="top"
                :content="scope.row.selectedSatelliteData"
                effect="dark"
            >
              <div class="text-ellipsis">
                {{ scope.row.selectedSatelliteData }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="指令代号"   align="center" prop="commandCode"  v-if="false" />
        <!--
                <el-table-column label="指令名称" align="center" prop="instructionCodeName"/>
        -->

        <el-table-column label="指令名称"   align="center" prop="instructionCodeName">
          <template #default="scope">
            <el-tooltip
                placement="top"
                :content="scope.row.instructionCodeName"
                effect="dark"
            >
              <div class="text-ellipsis">
                {{ scope.row.instructionCodeName }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>

        <!--
                <el-table-column label="指令码字" align="center" prop="instructionContent">
                  <template #default="scope">
                    <el-tooltip
                        placement="top"
                        :content="scope.row.instructionContent"
                        effect="dark"
                    >
                      <div class="text-ellipsis">
                        {{ scope.row.instructionContent }}
                      </div>
                    </el-tooltip>
                  </template>
                </el-table-column>-->

        <!--        <el-table-column label="指令码字" align="center" prop="instructionContent" />-->
        <el-table-column label="指令码字" align="center" >
          <template #default="scope">
            <el-tooltip
                placement="top"
                effect="light"
                popper-class="codeword-tooltip"
            >
              <template #content>
                <div class="tooltip-content">
                  {{ formatCommandCodeword(scope.row.instructionContent) }}
                </div>
              </template>
              <!-- 通过:class绑定动态绑定条件类名 -->
              <div
                  class="codeword-content"
                  :class="{ 'text-red': scope.row.instructionContent?.startsWith('参数错误') }"
              >
                {{ scope.row.instructionContent }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="absoluteDelayed" label="绝对延时" width="242">
          <template #default="scope">
            <div style="display:flex;flex-direction: row;align-items: center">
                  <span style="margin-left: 0">
                    <!-- 勾选框：控制当前行的 showAbsoluteDelayPicker -->
                    <el-checkbox
                        v-model="scope.row.showAbsoluteDelayPicker"
                        style="margin-right:4px"/>
                  </span>
              <!--   v-model="absoluteDelayed[ scope.$index ]"-->
              <el-date-picker
                  v-if="scope.row.showAbsoluteDelayPicker"
                  v-model="scope.row.absoluteDelayTime"
                  type="datetime"
                  placeholder="选择日期"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width:180px">
              </el-date-picker>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template #default="scope">
            <div style="align-items: center;white-space: nowrap;">

              <!-- 添加参数设置按钮 -->
              <el-button
                  size="small"
                  type="primary"
                  @click="openParameterSetting1s(scope.row.instructionCode,scope.row.instructionName,scope.row)"
                  plain
              >
                设参数
              </el-button>
              <el-button
                  size="small"
                  type="warning"
                  plain
                  @click="openDetailDlg(scope.row)"
                  v-show="!scope.row.instructionContent.startsWith('参数错误')"
              >
                准备发送
              </el-button>
              <!--
              <el-button type="success" size="small" @click="handleSend(scope.row)" plain
                         v-show="!scope.row.instructionContent.startsWith('参数错误')"
              >
                准备
              </el-button>
              -->
              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)" plain
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      </div>
<!--      <pagination
          v-show="zhunBeiFaSongTotal>0"
          :total="zhunBeiFaSongTotal"
          v-model:page="queryParamsDaiFaSongFenYe2.pageNum"
          v-model:limit="queryParamsDaiFaSongFenYe2.pageSize"
          @pagination="zhunBeiFaSunZhiLing"
          :page-sizes="[7]"
          :hide-on-single-page="false"
      />-->
      <el-row style="position: relative;height: 7.5%;min-height: 50px;">
        <el-col :span="24">
          <el-divider content-position="left">已发送</el-divider>
        </el-col>
      </el-row>


      <el-table :data="satelliteCommandList" >
        <!--            <el-table-column type="selection" width="55" align="center" />-->
        <el-table-column label="ID" align="center" prop="id"  v-if="false"  />
        <!--
                    <el-table-column label="卫星编号" align="center" prop="satelliteId" />
        -->


        <el-table-column label="卫星编号" align="center" prop="satelliteId">
          <template #default="scope">
            <el-tooltip
                placement="top"
                :content="scope.row.satelliteId"
                effect="dark"
            >
              <div class="text-ellipsis">
                {{ scope.row.satelliteId }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>


        <el-table-column label="指令代号" align="center" prop="commandCode"  v-if="false" />
        <!--            <el-table-column label="指令名称" align="center" prop="commandName" />-->


        <el-table-column label="指令名称" align="center" prop="commandName">
          <template #default="scope">
            <el-tooltip
                placement="top"
                :content="scope.row.commandName"
                effect="dark"
            >
              <div class="text-ellipsis">
                {{ scope.row.commandName }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>

        <!--            <el-table-column label="指令码字" align="center" prop="commandCodeword"/>-->
        <el-table-column label="指令码字" align="center">
          <template #default="scope">
            <el-tooltip
                placement="top"
                effect="light"
                popper-class="codeword-tooltip"
            >
              <template #content>
                <!-- 使用处理后的带换行的内容 -->
                <div class="tooltip-content">
                  {{ formatCommandCodeword(scope.row.commandCodeword) }}
                </div>
              </template>
              <div class="codeword-content"
              >
                {{ scope.row.commandCodeword }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="操作人" align="center" prop="createBy" />
        <el-table-column label="发送时间" align="center" prop="createTimes" />
        <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <div style="align-items: center;white-space: nowrap;">

            <!-- 添加参数设置按钮 -->
            <el-button
                size="small"
                type="primary"
                @click="viewParams(scope.row.id)"
                plain
            >
              查看参数
            </el-button>
          </div>
        </template>
      </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParamsFenYe2.pageNum"
          v-model:limit="queryParamsFenYe2.pageSize"
          @pagination="chaXunYiFaSongZhiLing"
          :page-sizes="[2]"
          :hide-on-single-page="false"
      />


      <!--

          <pagination
              v-show="total>0"
              :total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="getList"
          />


                <el-table style="position: relative;width: 100%;height: 70%;top: 0;border-radius: 8px">
                  <el-table-column label="指令代号" width="200">
                    <template #default="scope">
                      <div style="align-items: center">
                        <span style="margin-left: 0">{{ scope.row.remoteControlProtocol }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="指令名称" min-width="400">
                    <template #default="scope">
                      <div style="align-items: center">
                        <span style="margin-left: 0">{{ scope.row.remoteControlTemplate }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="指令码字" min-width="400">
                    <template #default="scope">
                      <div style="align-items: center">
                        <span style="margin-left: 0">{{ scope.row.remoteControlTemplate }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="绝对延时" min-width="150">
                    <template #default="scope">
                      <div style="align-items: center">
                        <span style="margin-left: 0">{{ scope.row.remoteControlTemplate }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="发送时间" min-width="150">
                    <template #default="scope">
                      <div style="align-items: center">
                        <span style="margin-left: 0">{{ scope.row.remoteControlTemplate }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" min-width="180">
                    <template #default="scope">
                      <div style="align-items: center;white-space: nowrap;">
                        <el-button type="success" size="small" @click="handleSend(scope.row)" plain>
                          发 送
                        </el-button>
                        <el-button
                            size="small"
                            type="danger"
                            @click="handleDelete(scope.$index, scope.row)" plain>
                          删 除
                        </el-button>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>-->
      <!--          <el-pagination
                    style="margin-top: 5px;margin-right: 3px;min-height: 50px;"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[10, 20, 30]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totals"/>-->

    </div>




  </div>


  <!-- 在适当位置添加参数设置对话框 -->
  <div>
    <ParameterSettings
        v-model:visible="parameterDialogVisible"
        :instructionCode="currentInstructionCode"
        :satelliteId="currentSatelliteId"
        :instructionName="currentInstructionName"
        :satelliteIds="currentSatelliteIds"
        :selectedSatelliteCodes="selectedSatelliteCodes"
        :zhunBeiFaSongZhiLingId="zhunBeiFaSongZhiLingId"
        @saved="handleParametersSaved"
    />
    <ParamDetailDialog
        v-model:visible="detailVisible"
        :sent-command-id="currentSentCommandId"/>
  </div>




  <!-- 描述列表弹窗 -->
  <el-dialog
      v-model="detailDlgVisible"
      title="准备发送 – 描述列表"
      width="95%"
      destroy-on-close
  >
    <!-- 查询按钮 -->

<!--
    <el-button
        type="primary"
        size="small"
        @click="queryParam(currentRow.commandCode)"
    >
      查询参数信息
    </el-button>-->
<!--

    <el-button type="success"
               @click="handleSend(rowObject)"
    >发送
    </el-button>

    <el-button
        type="danger"
        :icon="Close"
        @click="handleClose" >
      关闭
    </el-button>
-->

    <!-- 1. 把按钮放到 header 插槽里 -->
      <div class="dialog-header">
        <!-- 查询参数信息 -->
        <!--
        <el-button
          type="primary"
          size="large"
          @click="queryParam(currentRow.commandCode)"
        >
          查询参数信息
        </el-button>
        -->
        <el-button type="success" size="large" @click="handleSend(rowObject)">
          发送
        </el-button>

        <el-button type="danger" size="large" :icon="Close" @click="handleClose">
          关闭
        </el-button>
      </div>
<!--
    <el-button type="success" size="small"
               @click="handleSend(rowObject)"
    >发送
    </el-button>-->

    <el-descriptions
        :title="zhiLingMaZiCodeName"
        direction="vertical"
        :column="4"
        :size="size"
        border
    >
      <el-descriptions-item label="卫星编码">{{zhiLingMaZiWeiXing}}</el-descriptions-item>
      <el-descriptions-item label="指令">{{zhiLingMaZiCodeName}}</el-descriptions-item>
      <el-descriptions-item label="生成指令人" >{{caoZuoYuan}}</el-descriptions-item>
      <el-descriptions-item label="当前准备指令人" >{{dangQianRen}}</el-descriptions-item>


<!--      <el-descriptions-item label="Address">
        No.1188, Wuzhong Avenue, Wuzhong District, Suzhou, Jiangsu Province
      </el-descriptions-item>-->
      <el-descriptions-item label="指令码字"  :span="4">
        <el-input
            type="textarea"
            :rows="7"
            readonly
            :model-value=zhiLingMaZi
        />
      </el-descriptions-item>
<!--
      <el-descriptions-item label="使用参数"  :span="4">
        <el-input
            type="textarea"
            :rows="7"
            readonly
            :model-value="guDingZhiLists.map(item =>JSON.stringify(item.defaultValue)).join('\n\n')"
        />
      </el-descriptions-item>
-->
      <el-descriptions-item  :label="shiYongCanShuGeshu" :span="4">
        <!-- 用 v-html 渲染带样式的字符串 -->
        <div v-html="styledHexString" style="line-height: 28px;"></div>
      </el-descriptions-item>

      <el-descriptions-item label="使用参数"  :span="4">
        <el-input
            type="textarea"
            :rows="7"
            readonly
            :model-value="guDingZhiLists.map(item =>{
              let f = ''
              let f2 = `; 参数长度：`+item.parameterLength+`; 16进制=`
              if (item.processManner === '计算公式' || item.processManner === '公式计算') {
                // 变量名是运行时才拿到的
                const varName = item.parameterCode;   // 也可以是 'CmdParam2'、'PAR' ...
                const varValue = item.defaultValue;

                const vars = { [varName]: varValue };   // 计算属性写法
                let hex = `【` +calcToHex(item.parameterDefinition, vars, 0,item.parameterLength / 4) + `】`;
                // console.log('公式计算======',hex); // CmdParam1 = 180(0xB4) , 结果 = 65536(0x010000)
                f = f2 + hex
              }else {
                if( item.parameterType === '无符号整型' ){
                  console.log('带符号整型11====+ 无符号整型',item)

                let hex = `【` +padZero(Number(item.defaultValue).toString(16).toUpperCase(), item.parameterLength / 4) + `】`
                 f = f2 + hex
                }
                if(item.parameterType === '带符号整型'  ){
                  console.log('带符号整型22====+ 无符号整型',item)
                 let f2 = `; 参数长度：`+item.parameterLength+`; 16进制=`


                 f = f2 + `【` +intToHex(item.defaultValue,item.parameterLength/4) + `】`
                }
                if(item.parameterType === '16进制'  ){
                  console.log('带符号整型22====+ 无符号整型',item)
                 let f2 = `; 参数长度：`+item.parameterLength+`; 16进制=`

                // let hex = `【` +padZero(Number(item.defaultValue).toString(16).toUpperCase(), item.parameterLength / 4) + `】`
                let hex = `【` + item.defaultValue.replace('0x', '') + `】`
                 f = f2 + hex

                 // 下面这种方式会出现  如 0709的16进制  显示了709字符串，前面少0 的情况
                 // f = f2 + intToHex(item.defaultValue,item.parameterLength/4)
                }

                if(item.parameterType === '字典' ){
                  // console.log('字典====+ 字典',item)
                 let f2 = `; 参数长度：`+item.parameterLength+`; 16进制=`

                 f = f2 + `【` +intToHex(item.defaultValue,item.parameterLength/4) + `】`
                }
              }
              if(item.parameterDefinition === null || item.parameterDefinition === 'null'){
                item.parameterDefinition = '未定义'
              }
              return `${item.parameterSequence}: ${item.parameterName}= 【 ${item.defaultValue} 】       {（参数类型：${item.parameterType} ${f} ）（处理方式：${item.processManner}）（ 参数定义：${item.parameterDefinition}）}`;
            }).join('\n')"
        />
      </el-descriptions-item>

    </el-descriptions>




    <!-- 描述列表  删除后会所有不显示，只能隐藏不显示-->
    <el-descriptions v-show="false"
        :column="1"
        border
        style="margin-top:12px"
    >
      <!-- 每个片段独占一个 el-descriptions-item -->
      <el-descriptions-item
          v-for="(seg, idx) in segments"
          :key="idx"
      >
        <!-- 自定义 label -->
        <template #label>
          <span style="font-weight:bold">片段{{ idx + 1 }}</span>
        </template>

        <!-- 三列并排 -->
        <div style="display:flex;gap:16px">
        <span style="flex:2;font-family:monospace">
          <strong>码字：</strong>{{ seg.codeword }}
        </span>
          <span style="flex:1">
          <strong>参数：</strong>{{ seg.param || '-' }}
        </span>
          <span style="flex:1">
          <strong>固定值：</strong>{{ seg.fixed || '-' }}
        </span>
        </div>
      </el-descriptions-item>
    </el-descriptions>


    <!-- 第一个表格 -->

    <table>
      <tbody>
      <tr style="height: 1px; background-color: #c0cff1">
        <td colspan="8">包头（6字节）</td>
        <td colspan="3">数据域</td>
        <td colspan="4  " rowspan="1">参数详情</td>
      </tr>
      <tr style="height: 1px; background-color: #c0cff1">
        <td colspan="5">包识别</td>
        <td colspan="2">包序列控制</td>
        <td rowspan="3">包长度</td>
        <td rowspan="3">指令标识</td>
        <td rowspan="3">参数</td>
        <td rowspan="3">差错域</td>
        <td rowspan="5">
          <textarea
              :value="zu12"
              style="width: 700px; height: 120px; resize: none;">
          </textarea>
        </td>
      </tr>
      <tr style="height: 1px; background-color: #c0cff1">
        <td rowspan="2">版本号</td>
        <td rowspan="2">包类型</td>
        <td rowspan="2">副导头标识</td>
        <td colspan="2">过程标识符</td>
        <td rowspan="2">包序列标识</td>
        <td rowspan="2">包序列计数</td>
      </tr>
      <tr style="height: 1px; background-color: #c0cff1">
        <td>模块标识</td>
        <td>数据类型</td>
      </tr>
      <tr style="height: 1px; background-color: #c0cff1">
        <td>3bits</td>
        <td>1bit</td>
        <td>1bit</td>
        <td>7bits</td>
        <td>4bits</td>
        <td>2bits</td>
        <td>14bits</td>
        <td>16bits</td>
        <td>16bits</td>
        <td>N*16bit</td>
        <td>16bits</td>
      </tr>
      <tr style="height: 1px;">
        <td colspan="5">{{zu8}}</td>
        <td colspan="2">{{zu9}}</td>
        <td>{{zu10}}</td>
        <td>{{zu11}}</td>
        <td>
          <textarea> {{zu12}}</textarea>
          </td>
        <td>{{zu13}} </td>
      </tr>
      </tbody>
    </table>
<div style="height: 10px;"></div>
    <!-- 第二个表格 -->

    <table>
      <tbody>
      <tr style="height: 1px; background-color: #c0cff1">
        <td rowspan="1">同步序列</td>
        <td colspan="14">帧头（12字节）</td>
        <td colspan="4">数据域</td>
        <td rowspan="3">差错控制域
          （2字节）</td>
      </tr>
      <tr style="height: 1px; background-color: #c0cff1">
        <td rowspan="3">1ACFFC1D</td>
        <td colspan="3">标识域（4字节）</td>
        <td colspan="11">协议域（8字节）</td>
        <td colspan="2">M-PDU导头</td>
        <td rowspan="3">M-PDU包</td>
        <td rowspan="3">空闲数据区</td>
      </tr>
      <tr style="height: 1px; background-color: #c0cff1">
        <td rowspan="2">轨道面标识</td>
        <td rowspan="2">航天器标识(SCID)</td>
        <td rowspan="2">设备标识</td>
        <td rowspan="2">标
          识
          域
          类
          型</td>
        <td rowspan="2">回
          放
          标
          识</td>
        <td rowspan="2">旁路/
          顺序
          控制
          标志</td>
        <td rowspan="2">协议
          控制
          命令
          标志</td>
        <td rowspan="2">保留</td>
        <td rowspan="2">保留</td>
        <td rowspan="2">帧长
          度</td>
        <td rowspan="2">服务
          类型</td>
        <td rowspan="2">信道
          类型</td>
        <td rowspan="2">虚拟信
          道标识
          (VCID)</td>
        <td rowspan="2">虚拟信道帧计
          数
          (VCFC)</td>
        <td rowspan="2">保留
          域</td>
        <td rowspan="2">A42</td>
      </tr>
      <tr style="height: 1px; background-color: #c0cff1">
        <td>首导头指
          针</td>
      </tr>
      <tr style="height: 1px; background-color: #c0cff1">
        <td style="height: 1px;"><span style="height: 2px;">32bits</span> </td>
        <td>16bits</td>
        <td>08bits</td>
        <td>08bits</td>
        <td>1bit</td>
        <td>1bit</td>
        <td>1bit</td>
        <td>1bit</td>
        <td>4bits</td>
        <td>3bits</td>
        <td>5bits</td>
        <td>4bits</td>
        <td>4bits</td>
        <td>8bits</td>
        <td>32bits</td>
        <td>5bits</td>
        <td>11bits</td>
        <td>N Bytes</td>
        <td>L-N Bytes</td>
        <td>16bit</td>
      </tr>
      <tr>
        <td>{{zu1}}</td>
        <td colspan="3">{{zu2}}</td>
        <td colspan="5">{{zu3}}</td>
        <td colspan="2">{{zu4}}</td>
        <td colspan="3">{{zu5}}</td>
        <td>{{zu6}}</td>
        <td colspan="2">{{zu7}}</td>
        <td> </td>
        <td> </td>
        <td>{{zu15}}</td>
      </tr>
      </tbody>
    </table>

  </el-dialog>











</template>

<style scoped>
.instruct-send-main {
  position: relative;
  width: 99%;
  height: 100%;
  margin-top: 0;
  margin-left: auto;
  margin-right: auto;

  border-radius: 10px;

  display: flex;
  flex-direction: row;
  justify-content: center;
}

.branch-types-left {
  position: absolute;
  width: 20%;
  height: 100%;
  top: 0;
  left: 0;

  border-color: #bebebe;
  border-top: 1px solid;
  border-left: 1px solid;
  border-bottom: 1px solid;
  border-radius: 8px;
}



.send-instruct-right {
  position: absolute;
  width: 78%;
  height: 100%;
  left: 20%;
  top: 0;
  right: 0;

  border: solid 1px #bebebe;
  border-radius: 8px;
}

.instruct-search {
  position: relative;
  width: 100%;
  margin-top: 10px;
  margin-bottom: 10px;

  display: flex;
  flex-direction: row;
}

.instruct-collapse {
  position: relative;
  width: 100%;
  background-color: #f5f5f5;
}

.history-paging {
  position: relative;
  width: 96%;
  margin-top: 5px;
  right: 3px;
}

/* 控制指令码字列的内容显示长度 */
.content-limit {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  cursor: pointer; /* 鼠标变为指针，提示可查看完整内容 */
  padding: 0 4px; /* 增加一点内边距，避免内容太贴边 */
}


/* 限制单元格显示长度，超出部分显示省略号 */
.codeword-content {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
 /* max-width: 200px;*/ /* 根据需要调整最大显示宽度 */
}

/* 自定义提示框样式 */
:deep(.codeword-tooltip) {
  max-width: 200px; /* 提示框最大宽度 */
  padding: 8px 12px;
  word-wrap: break-word; /* 自动换行 */
  white-space: normal; /* 允许正常换行 */
}

.text-ellipsis {
  white-space: nowrap;    /* 不换行 */
  overflow: hidden;       /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 显示省略号 */
  max-width: 100%;        /* 最大宽度为父容器宽度 */
}

/* 深度选择器穿透 scoped 样式 */
.custom-table:deep( .el-table__row) {
  height: 1px; /* 行高（关键） */
}

.custom-table:deep(.el-table__cell)  {
  padding: 0 8px; /* 调整单元格内边距（上下 0，左右 8px） */
  line-height: 1px; /* 行高等于行高，确保垂直居中 */
  white-space: nowrap; /* 禁止文本换行（可选，防止内容撑开高度） */
  overflow: hidden; /* 隐藏溢出内容（可选） */
  text-overflow: ellipsis; /* 溢出显示省略号（可选） */
}
/* 外层容器：控制整体位置和边框 */
.table-outer-container {
  width: 100%;
  margin: 0 16px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden; /* 防止内部滚动条溢出边框 */
}

/* 强制表头固定（Element表格设置height后会自动生成固定表头） */
:deep(.el-table__header-wrapper) {
  position: sticky !important;
  top: 0 !important;
  z-index: 2 !important;
  background-color: #fff !important;
}

/* 确保内容区滚动条正常显示 */
:deep(.el-table__body-wrapper) {
  overflow-y: auto !important;
}

/* 修复表头与内容区的边框冲突 */
:deep(.el-table__header-wrapper .el-table__header) {
  border-bottom: 1px solid #e8e8e8 !important;
}

/* 清除可能影响的全局样式 */
:deep(.el-table) {
  border: none !important;
}
:deep(.el-table__cell) {
  background-color: inherit !important;
}




table {
  border-collapse: collapse; /* 合并边框，使表格间隔为0 */
}
td {
  border: 1px solid #000; /* 表格边框 */
  padding: 2px; /* 单元格内边距，可根据需要调整 */
  text-align: center; /* 内容居中 */
}
.text-red {
  color: #ff4d4f; /* 使用Element UI的危险色红色 */
}

/* 或者直接通过style绑定 */
/*
<div
  class="codeword-content"
  :style="{ color: scope.row.commandCodeword?.startsWith('参数错误') ? '#ff4d4f' : '' }"
>
*/

.el-descriptions__body {
  font-size: 18px;   /* 整体放大 */
}

.dialog-header {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 306px;            /* 按钮间距 */
}


.search-btn {
  border: 1px solid #409eff !important;
}
.search-item {
  padding: 6px 0;
  font-size: small;
  cursor: pointer;
}
.search-item:hover {
  background: #f5f7fa;
}
/* 让按钮与文字垂直居中 */
.el-divider__text {
  display: inline-flex;
  align-items: center;
}
</style>
